package practise;

import java.util.Stack;

public class IsValid {

    private int indexOf(Character[] types, Character type) {
        for (int i = 0; i < types.length; i++) {
            if(types[i].equals(type)) {
                return i;
            }
        }
        return -1;
    }

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        stack.push('1');// 防止空栈异常
        Character[] left = {'{', '(', '['};
        Character[] right = {'}', ')', ']'};

        int indexLeft = -1;
        int indexRight = -1;
        for (int i = 0; i < s.length(); i++) {
            Character c = s.charAt(i);
            int index;
            if((index = indexOf(left, c)) != -1) {
                // 说明是左括号
                stack.push(c);
                indexLeft = index;
            } else if((index = indexOf(right, c)) != -1) {
                // 说明是右括号
               /*
                    // 因为 index 不会为 -1 而没有左括号也是为 -1 就会走 indexRight != indexLeft
                    // 先判断一下有没有左括号
                    if(indexLeft == -1) {
                        return false;
                    }
                */
                // 再判断一下是否对应
                indexRight = index;
                if(indexRight != indexLeft) {
                    // 不相同，那么就错误
                    return false;
                }
                //那么就弹出 并把 indexLeft 更新一下
                stack.pop();
                indexLeft = indexOf(left, stack.peek());
            }
        }
        return stack.size() == 1;// 因为上面 push(1)
    }
}
